use std::env;
use std::fmt::Debug;
use std::ops::Add;
use std::time;
use chrono::Local;

#[derive(Default,Debug)]
pub struct SidecarConfig {
    pub server_addr: String,
    pub container_port: u32,
    pub version: String,
    pub service_name:String,
    pub service_ip: String,
}

impl SidecarConfig {
    pub fn new_from_arg() -> Self {
        let args : Vec<String> = env::args().collect();
        let mut config = SidecarConfig::default();
        let mut sip= String::from("127.0.0.1");
        let mut version= String::from("v1");
        let mut port = 8080;
        let mut tip= String::from("127.0.0.1");
        let mut pod_name= String::new();

        for arg in args {
            if arg.contains("=") {
                let (_,other) = arg.split_at(1);
                if let Some((key,value)) = other.split_once("=") {
                    match key {
                        "sip"=> sip = value.to_string(),
                        "version"=>version = value.to_string(),
                        "port" =>port = value.to_string().parse::<u32>().unwrap(),
                        "tip" => tip = value.to_string(),
                        _ => {}
                    }
                }
            }
        }

        if let Ok(data) = env::var("POD_NAME") {
            pod_name = data;
        } else {
            pod_name =  Local::now().timestamp().to_string();
        }

        config.version = version;
        config.container_port = port;
        config.service_ip = tip;
        config.service_name = pod_name;
        config.server_addr = sip.add(":19898");

        config
    }
}


#[cfg(test)]
mod test {
    use crate::flags::SidecarConfig;

    #[test]
    fn test() {
        let a = SidecarConfig::new_from_arg();
        println!("{:?}",a);
    }
}